<?php
include'Utils.php';
class FacultiesController extends AppController{

	public $components = array('Subject', 'CenterInfo', 'Pic', 'MainInfo', 'FacultySubject', 'Course');

	function listFaculties(){
		$subjects = $this->Subject->getListSubject();
		$this->set('subjects', $subjects);
		$centerInfo = $this->CenterInfo->getInfo();
		$this->set('center_info', $centerInfo);
		$mainImageList = $this->Pic->getMainImageList();
		$this->set('main_images', $mainImageList);
		$mainInfo = $this->MainInfo->getInfo();
		$this->set('main_info', $mainInfo);
		$faculties = $this->Faculty->find('all');
		$courses = $this->Course->getAll();
		$this->set('courses', $courses);
		$responeFaculties = array();
		foreach ($faculties as $faculty):
			$fctId = $faculty['Faculty']['m_fct_id'];
			$subIds = $this->FacultySubject->getSubIdByFaculty($fctId);
			$subjects = array();
			foreach ($subIds as $subId):
				$subject = $this->Subject->getSubjectById($subId['FacultiesSubject']['sub_id']);
				array_push($subjects, $subject[0]['Subject']);
			endforeach;
			$faculty['Subject'] = $subjects;
			array_push($responeFaculties, $faculty);
		endforeach;
		$this->set('faculties', $responeFaculties);
	}
	
	/**
	 * Index, get all faculties
	 */
	function index(){
		// Check session and redirect to login page
		Utils::checkSession($this);
		$this->set('admin', '1');
		
		$centerInfo = $this->CenterInfo->getInfo();
		$this->set('center_info', $centerInfo);
		
		/* Get all faculties from DB */
		$faculties = $this->Faculty->find('all');
		
		/* Append subjects of each faculty and make new faculty list */
		$hasSubjectsFaculties = array();
		foreach ($faculties as $faculty):
			$facultyId = $faculty['Faculty']['m_fct_id'];
			$subIds = $this->FacultySubject->getSubIdByFaculty($facultyId);
			$subjects = array();
			
			foreach ($subIds as $subId):
				$subject = $this->Subject->getSubjectById($subId['FacultiesSubject']['sub_id']);
				array_push($subjects, $subject[0]['Subject']);
			endforeach;
			$faculty['Subject'] = $subjects;
			
			array_push($hasSubjectsFaculties, $faculty);
		endforeach;
			
		$this->set('faculties', $hasSubjectsFaculties);
		if ($this->request->is('post')){
			if (!isset($_POST['submitType'])){
				$this->redirect(array('action' => 'index'));
			}else{
				$this->FacultySubject->deleteAllByFacultyId($_POST['facultyId']);
				$this->Faculty->deleteAll(array('Faculty.m_fct_id' => $_POST['facultyId']), false);
				unlink("faculty/".$_POST['facultyFile']);
				$this->redirect(array('action' => 'index'));
			}
		}
	}
	
	/**
	 * Add faculty
	 */
	function faculty_add(){
		// Check session and redirect to login page
		Utils::checkSession($this);
		$this->set('admin', '1');
		
		if (isset($_POST['isBack'])){
			if (isset($_POST['facultyTempFile'])){
				unlink("temp/upload_temp/".$_POST['facultyImage']);
			}
		}
		
		$centerInfo = $this->CenterInfo->getInfo();
		$this->set('center_info', $centerInfo);
		
		$subjects = $this->Subject->getListSubject();
		$this->set('subjects', $subjects);
		
		/* When go back from confirm */
		$facultyName    = (isset($_POST['facultyName'])) ? $_POST['facultyName'] : "";
		$facultyEmail   = (isset($_POST['facultyEmail'])) ? $_POST['facultyEmail'] : "";
		$facultyTel     = (isset($_POST['facultyTel'])) ? $_POST['facultyTel'] : "";
		$facultyMobile  = (isset($_POST['facultyMobile'])) ? $_POST['facultyMobile'] : "";
		$facultyDesc    = (isset($_POST['facultyDesc'])) ? $_POST['facultyDesc'] : "";
		
		$this->set('facultyName'   , $facultyName  );
		$this->set('facultyEmail'  , $facultyEmail );
		$this->set('facultyTel'    , $facultyTel   );
		$this->set('facultyMobile' , $facultyMobile);
		$this->set('facultyDesc'   , $facultyDesc  );
	}
	
	/**
	 * Edit faculty
	 */
	function faculty_edit(){
		// Check session and redirect to login page
		Utils::checkSession($this);
		$this->set('admin', '1');
		
		if (isset($_POST['isBack'])){
			if (isset($_POST['facultyTempFile'])){
				unlink("temp/upload_temp/".$_POST['facultyImage']);
			}
		}
		
		$centerInfo = $this->CenterInfo->getInfo();
		$this->set('center_info', $centerInfo);
		
		$subjects = $this->Subject->getListSubject();
		$this->set('subjects', $subjects);
		
		if(!isset($_POST['facultyId']))
			$this->redirect(array('action' => 'index'));
			
		$facultyId = $_POST['facultyId'];
		$faculty = $this->Faculty->findBym_fct_id($facultyId);
		
		$subIdsOfFct = array();
		if (isset($_POST["facultySubIds"])){
			if (strlen($_POST['facultySubIds']) > 0){
				$subIds = explode("," , $_POST['facultySubIds']);
				foreach ($subIds as $subId):
					array_push($subIdsOfFct, $subId);
				endforeach;
			}
		}else{
			$subsOfFct = $this->FacultySubject->getSubIdByFaculty($facultyId);
			foreach($subsOfFct as $sub):
				array_push($subIdsOfFct, $sub['FacultiesSubject']['sub_id']);
			endforeach;
		}
		$this->set('subIdsOfFct', $subIdsOfFct);
		
		$facultyName    = (isset($_POST['facultyName'])) ? $_POST['facultyName'] : $faculty['Faculty']['m_fct_name'];
		$facultyEmail   = (isset($_POST['facultyEmail'])) ? $_POST['facultyEmail'] : $faculty['Faculty']['m_fct_email'];
		$facultyTel     = (isset($_POST['facultyTel'])) ? $_POST['facultyTel'] : $faculty['Faculty']['m_fct_tel'];
		$facultyMobile  = (isset($_POST['facultyMobile'])) ? $_POST['facultyMobile'] : $faculty['Faculty']['m_fct_mobile'];
		$facultyDesc    = (isset($_POST['facultyDesc'])) ? $_POST['facultyDesc'] : $faculty['Faculty']['m_fct_descript'];
		$facultyImage   = $faculty['Faculty']['m_fct_image'];
		
		$this->set('facultyId'     , $facultyId);
		$this->set('facultyName'   , $facultyName  );
		$this->set('facultyEmail'  , $facultyEmail );
		$this->set('facultyTel'    , $facultyTel   );
		$this->set('facultyMobile' , $facultyMobile);
		$this->set('facultyDesc'   , $facultyDesc  );
		$this->set('facultyImage'  , $facultyImage  );
	}
	
	/**
	 * Confirm posted faculty information
	 */
	function faculty_confirm(){
		// Check session and redirect to login page
		Utils::checkSession($this);
		$this->set('admin', '1');
		
		$centerInfo = $this->CenterInfo->getInfo();
		$this->set('center_info', $centerInfo);
		
		if(isset($_POST['facultyId']))
			$this->set('facultyId',  $_POST["facultyId"]);
		
		$this->set('facultyMobile',  isset($_POST["facultyMobile"]) ? $_POST["facultyMobile"] : "");
		$this->set('facultyTel',  isset($_POST["facultyTel"]) ? $_POST["facultyTel"] : "");
		$this->set('facultyName',  isset($_POST["facultyName"]) ? $_POST["facultyName"] : "");
		$this->set('facultyEmail', isset($_POST["facultyEmail"]) ? $_POST["facultyEmail"] : "");
		$this->set('facultyDesc', isset($_POST["facultyDesc"]) ? htmlentities($_POST["facultyDesc"], ENT_QUOTES, 'utf-8') : "");
		
		if (isset($_POST["facultyOldImage"])){
			$this->set('facultyOldImage', $_POST["facultyOldImage"]);
			}
			
		$fctSubNames = '';
		$fctSubIds = '';
		if(isset($_POST['facultySubIds'])){
			foreach ($_POST["facultySubIds"] as $subId):
				$subject = $this->Subject->getSubjectById($subId);
				if ($fctSubNames == '')
					$fctSubNames = $subject[0]['Subject']['sub_name'];
				else
					$fctSubNames = $fctSubNames ." , ". $subject[0]['Subject']['sub_name'];	
					
				if ($fctSubIds == '')
					$fctSubIds = $subId;
				else 
				 	$fctSubIds = $fctSubIds.",".$subId;
			endforeach;
		}
		$this->set('facultySubIds', $fctSubIds);
		$this->set('fctSubNames', $fctSubNames);

		/* FILE */
		if (!isset($_FILES["file"])){
			$this->set('facultyImage', $_POST["facultyImage"]);
			return;
		}
		
		$this->set('facultyImage', $_FILES["file"]["name"]);
		if (strlen($_FILES["file"]["name"]) == 0)
			return;
			
		if ($_FILES["file"]["error"] > 0) {
			echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
		} else {
			$this->set('facultyTempFile', $_FILES["file"]["tmp_name"]);
			move_uploaded_file($_FILES["file"]["tmp_name"],
			"temp/upload_temp/" .$_FILES["file"]["name"]);
		}
	}
	
	function facultyRegist(){
		if($this->request->is('post')){
			if(isset($_POST['facultyId'])){
				if(!isset($_POST["facultyDesc"]) || !isset($_POST['facultyName']) || !isset($_POST['facultyImage']) ||
				   !isset($_POST['facultyEmail']) || !isset($_POST['facultyTel']) || !isset($_POST['facultyMobile'])){
				   	$this->redirect(array('action' => 'index'));
				   }
				   
				$dataNeedToSave = array('Faculty.m_fct_name' => "'".$_POST["facultyName"]."'",
						                'Faculty.m_fct_image' => "'".$_POST["facultyImage"]."'",
						                'Faculty.m_fct_email' => "'".$_POST["facultyEmail"]."'",
				 						'Faculty.m_fct_tel' => "'".$_POST["facultyTel"]."'",
										'Faculty.m_fct_mobile' => "'".$_POST["facultyMobile"]."'",
										'Faculty.m_fct_descript' => "'".htmlentities($_POST["facultyDesc"], ENT_QUOTES, 'utf-8')."'",
										);
				
				$saveCondition = array('Faculty.m_fct_id' => $_POST['facultyId']);
				if ($this->Faculty->updateAll($dataNeedToSave, $saveCondition)) {
					if (isset($_POST['facultyTempFile'])){
						/* Delete old image */
						if ((isset($_POST['facultyOldImage'])) && (strlen($_POST['facultyOldImage']) > 0))
							unlink("faculty/".$_POST['facultyOldImage']);
							
						copy("temp/upload_temp/".$_POST['facultyImage'],
							"faculty/" .$_POST['facultyImage']);
						unlink("temp/upload_temp/".$_POST['facultyImage']);
						}
						
					/* Update faculty_subject */
					if (strlen($_POST['facultySubIds']) > 0){
						$subIds = explode("," , $_POST['facultySubIds']);
						$this->FacultySubject->deleteAllByFacultyId($_POST['facultyId']);
						foreach ($subIds as $subId):
							$this->FacultySubject->addRecord($_POST['facultyId'], $subId);
						endforeach;
					}
					$this->redirect(array('action' => 'index'));
				}
			}else{
				if(!isset($_POST["facultyDesc"]) || !isset($_POST['facultyName']) || !isset($_POST['facultyImage']) ||
				   !isset($_POST['facultyEmail']) || !isset($_POST['facultyTel']) || !isset($_POST['facultyMobile'])){
				   	$this->redirect(array('action' => 'index'));
				   }
				   
				$this->Faculty->create();
				$dataNeedToSave = array('Faculty' => array('m_fct_name' => $_POST['facultyName'],
						                'm_fct_image' => $_POST['facultyImage'],
						                'm_fct_email' => $_POST['facultyEmail'],
						                'm_fct_tel' => $_POST['facultyTel'],
										'm_fct_mobile' => $_POST['facultyMobile'],
										'm_fct_descript' => htmlentities($_POST['facultyDesc'], ENT_QUOTES, 'utf-8')));
				
				if($this->Faculty->save($dataNeedToSave)){
					if (isset($_POST['facultyTempFile'])){
						copy("temp/upload_temp/".$_POST['facultyImage'],
							 "faculty/" .$_POST['facultyImage']);
						unlink("temp/upload_temp/".$_POST['facultyImage']);
					}
					
					/* Update faculty_subject */
					if (strlen($_POST['facultySubIds']) > 0){
						$subIds = explode("," , $_POST['facultySubIds']);
						$this->FacultySubject->deleteAllByFacultyId($this->Faculty->id);
						foreach ($subIds as $subId):
							$this->FacultySubject->addRecord($this->Faculty->id, $subId);
						endforeach;
					}
					$this->redirect(array('action' => 'index'));
				}
			}
		}
	}
	
	/**
	 * 
	 * Function used to check if image existed???
	 * @param String $imageName
	 */
	public function checkImageExist(){
		$imageName = $_POST['image_name'];
		if (strlen($imageName) == 0){
			echo ""; die;
		}
		
		/* Move image of this faculty to delete_temp before checking
		 * In order to allow user post same image file name for this faculty
		 */
		if((isset($_POST['facultyOldImage']) && (strlen($_POST['facultyOldImage'])))){
			copy("faculty/".$_POST['facultyOldImage'],
			 	"temp/delete_temp/".$_POST['facultyOldImage']);
			unlink("faculty/".$_POST['facultyOldImage']);
		}
		
		$fileError = false;
		if (file_exists("faculty/".$imageName)){
			$fileError = true;
		}
		
		if((isset($_POST['facultyOldImage']) && (strlen($_POST['facultyOldImage'])))){
			/* Move file back */
			copy("temp/delete_temp/".$_POST['facultyOldImage'], 
			     "faculty/".$_POST['facultyOldImage']);
			unlink("temp/delete_temp/".$_POST['facultyOldImage']);
		}
		
		if ($fileError == true){
			echo "File ".$imageName." đã tồn tại";die;
		}else{
			echo ""; die;
		}
	}
}
?>